﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml.Linq;
using System.Xml.XPath;
using System.ComponentModel;
using System.Drawing.Design;

namespace SharingCenter.Web.Shared
{
    public partial class GenericTabs : System.Web.UI.UserControl
    {
        //[UrlProperty, Editor(typeof(GenericTabs), typeof(UITypeEditor))]
        //public string LinkListXmlPath { get; set; }
        //public string LinkListXPath { get; set; }
        public string SelectedItem { get; set; }
        public string Section { get; set; }
        public bool AddPageQueryString { get; set; }
        public string PreservedQueryStringFields { get; set; }

        protected void Page_Load(object sender, EventArgs e)
        {
            /*
            XDocument doc = null;
            try
            {
                doc = XDocument.Load(HttpContext.Current.Server.MapPath(LinkListXmlPath));
            }
            catch { }
            List<XElement> l = (doc.XPathSelectElements(LinkListXPath)).ToList();
             */
            //XmlDataSource1.DataFile = LinkListXPath;
            try
            {
                XmlDataSource1.XPath = string.Format("//Section[@Name='{0}']/Link", Section);
            }
            catch { }

        }

        protected void HyperLink1_PreRender(object sender, EventArgs e)
        {
            string qs = string.Empty;
            if (AddPageQueryString)
            {
                if (PreservedQueryStringFields != null && PreservedQueryStringFields.Trim() != string.Empty)
                {
                    string preserved = PreservedQueryStringFields.Trim();
                    char[] sep = { ';', ',', '|' };
                    string[] fields = preserved.Split(sep);
                    List<string> queryList = new List<string>();
                    for(int i=0; i<fields.Length; i++)
                    {
                        fields[i] = fields[i].Trim();
                        queryList.Add(string.Format(@"{0}={1}", fields[i], Request.QueryString[fields[i]]));
                    }
                    qs = string.Join(@"&", queryList.ToArray());
                }
                else
                {
                    qs = HttpContext.Current.Request.Url.Query;
                }
            }

            if (qs.StartsWith("?"))
            {
                qs = qs.Substring(1);
            }

            HyperLink s = (HyperLink)sender;
            if (qs.Length > 0)
            {
                if (s.NavigateUrl.Contains("?"))
                {
                    s.NavigateUrl += "&" + qs;
                }
                else
                {
                    s.NavigateUrl += "?" + qs;
                }
            }
        }
    }
}